import { getPlayerInfo, addFriend } from '../../../http/game'
import { getAuth } from '../../../utils/account'
const app = getApp()
const socketUrl = app.globalData.socketHost
var socketStatus = 'closed'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        staticUrl: app.globalData.staticUrl,
        playerInfo: {
            nickname: '',
            msg: '',
            headimg: ''
        },
        game_disabled: false,
        friend_disabled: false,
        userInfo:app.globalData.userInfo,
    },

    onLoad: function(options) {
        const isAuth = !!app.globalData.userInfo&& !!app.globalData.userInfo.token
        this.setData({ isAuth });
        var { id, type, time, c, match_billno } = options
        console.log(options);
        if(options.scene){
            console.log(options.scene);
             
             var scense =  decodeURIComponent(options.scene).split('&');
             if(scense.length == 3){
                    match_billno = scense[0];
                    id = scense[1];
                    c = scense[2];
             }
             if(scense.length == 1){
                 id = scense[0];
                wx.setNavigationBarTitle({
                  title: '加为好友',
                })
            }
        }
        console.log(match_billno);
        this.setData({ id, type, time, c, match_billno })
        if (isAuth) {
           
            this.getPlayerInfo()
        } else {
            getAuth(options)
        }
    },
    onShow: function() {
        
        var  isAuth =  !!app.globalData.userInfo&& !!app.globalData.userInfo.token
        if (isAuth) {
        
            this.getPlayerInfo()
            this.websocketGame()
        } else {
            getAuth()
        }
    },
    // 获取玩家信息
    async getPlayerInfo() {
        const { id, type, c } = this.data
        console.log(id);
        const { data } = await getPlayerInfo({ id, type, c })
        this.setData({
            playerInfo: data
        })
    },
    // 加为好友
    async addFriend() {
        if (!this.data.isAuth) {
            getAuth()
            return
        }
        if (this.data.disabled) {
            return
        }
        let{userInfo} = this.data;
        userInfo = app.globalData.userInfo;
        var player_id = userInfo.player_id;
        if(!player_id){
            wx.showToast({
              title: '请先加入球员信息',
              duration:2000,
            })
            setTimeout(function() {
                wx.navigateTo({
                  url: '../../More/information/information',
                })
            },  2000)
            return ;
        }
        this.setData({userInfo});
        await addFriend({ in_player_id: this.data.id,player_id:player_id,type_id:1 }).then(res => {
            if (res.code == 1) {
                this.setData({
                    friend_disabled: true
                })
                wx.showToast({
                    title: res.info,
                    icon: 'none',
                    duration: 2000,
                    success: (res) => {}
                })
            }
        })
    },
    // 进入球局
    enterGame() {
        if (!this.data.isAuth) {
            getAuth()
            return
        } else {

            let{match_billno} = this.data;
            const {nickName , player_id, avatarUrl } =app.globalData.userInfo
            if(!player_id){
                wx.showToast({
                  title: '请先加入球员信息',
                  duration:2000,
                })
                setTimeout(function() {
                    wx.navigateTo({
                      url: '../../More/information/information',
                    })
                },  2000)
                return ;
            }
            const players_info = {
                player_id: player_id,
                avatarUrl: avatarUrl,
                nickName: nickName
            }
            const params = {
                id: this.data.id, //对方的id
                players_info: players_info, //我的信息
                match_billno:match_billno,
                type:'join', //进入球局
            }
            console.log(params,'发送消息');
            this.sendMessage(params)
        }
    },
    websocketGame() {
            this.closeSocket();
            this.openSocket();
        
    },
    openSocket() {
        let{match_billno} = this.data;
        const {nickName , player_id, avatarUrl } =app.globalData.userInfo
        const players_info = {
            player_id: player_id,
            avatarUrl: avatarUrl,
            nickName: nickName
        }
        const params = {
            id: this.data.id, //对方的id
            players_info: players_info, //我的信息
            match_billno:match_billno,
        }
        var that = this;
        var timer = setInterval(function() {
            app.websocketrevice(params,function(res) {
                    if(res.data){
                        that.handleSocket(res.data.data);
                    }
            },function() {

            })
        },10000);
            this.setData({timer});
    },
    //关闭信道
    closeSocket() {
       if(this.data.timer){
        clearInterval(this.data.timer);
       }
    },
    //发送消息函数
    sendMessage(params) {

            app.websocketsend(params,function(res) {
                wx.showToast({
                  title: '申请已发出,等待对方处理',
                })
            },function() {

            })
    
    },
    // 处理socket消息
    handleSocket(response) {
        const my_id = this.data.userInfo.player_id;
        console.log(response, this.data.match_billno, my_id)
        console.log(response.code == 1, response.match_billno === this.data.match_billno)
        if (response.code == 1 && response.match_billno === this.data.match_billno) { // 加入成功,等待创建 code=1
            if (response.players_info.player_id == my_id) {
                this.setData({
                    game_disabled: true
                })
            }
            console.log(this.data.game_disabled, 'game_disabled')
        } else if (response.code == 2) { // 创建成功 code=2
            if (response.ids.includes(my_id) && response.match_billno == this.data.match_billno) {
                const { match_billno, match_id } = response
                console.log(match_billno, match_id)
                wx.redirectTo({
                    url: `/pages/Personal_matches/match/match?match_id=${match_id}&pm_billno=${match_billno}`,
                })
            }
        } else if (response.code == 3 && response.match_billno == this.data.match_billno) { // 踢出球局 code=3
            wx.showToast({
                title: '您已被踢出球局',
                icon: 'none',
                duration: 2000
            })
            setTimeout(() => {
                this.closeSocket()
                wx.switchTab({
                    url: '/pages/index/index',
                })
            }, 2000)
        } else if (response.code == 4 && response.match_billno == this.data.match_billno) { // 重复进入
            wx.showToast({
                title: '您已加入过球局',
                icon: 'none',
                duration: 2000
            })
            // wx.showModal({
            //     title: '提示',
            //     content: '您已加入过球局，是否前往？',
            //     confirmText: '前往',
            //     confirmColor: '#cd0808',
            //     success:res=>{
            //         if(res.confirm){
            //             wx.navigateTo({
            //               url: `/pages/index/gamelist/gamecard/gamecard?match_id=${match_id}&pm_billno=${match_billno}`,
            //             })
            //         }
            //     }
            // })
        } else if (response.code == -1) { //加入创建失败
            wx.showToast({
                title: '二维码已失效，请重新扫码',
                icon: 'none',
                duration: 2000
            })
            setTimeout(() => {
                this.closeSocket()
                wx.switchTab({
                    url: '/pages/index/index',
                })
            }, 2000)
        }else if(response.code == ''){
            console.log('没有消息更新');
        } 
        else {
            wx.showToast({
                title: '参数不匹配',
                icon: 'none'
            })
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },



    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {
        this.closeSocket()
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },
})